package com.ld.shieldsb.common.web.tag;

import java.io.IOException;

import javax.servlet.jsp.tagext.SimpleTagSupport;

import org.springframework.web.servlet.resource.ResourceUrlProvider;

import com.ld.shieldsb.common.core.util.SpringContextHolder;

import lombok.extern.slf4j.Slf4j;

/**
 * 根据资源的内容计算Hex MD5哈希值，并将其附加到文件名。 例如："styles/main-e36d2e05253c6c7085a91522ce43a0b4.css"<br>
 * 需要在配置文件中增加以下配置启用：<br>
 * # 静态资源缓存相关 <br>
 * spring.resources.chain.strategy.content.enabled=true<br>
 * # 启用缓存，建议在服务器上关闭 <br>
 * spring.resources.chain.cache=false<br>
 *
 * @author hansai
 * @date 2019-05-24
 */
@Slf4j
public class GetResourceVersionTag extends SimpleTagSupport {

    /**
     * 资源路径
     */
    private String lookupPath;

    /**
     * 利用 {@link ResourceUrlProvider} 获取，耗时在百毫秒左右
     */
    @Override
    public void doTag() {
        try {
            ResourceUrlProvider resourceUrlProvider = SpringContextHolder.getBean(ResourceUrlProvider.class);
            this.getJspContext().getOut()
                    .print(resourceUrlProvider != null ? resourceUrlProvider.getForLookupPath(lookupPath) : lookupPath);
        } catch (IOException e) {
            log.error("静态资源追加md5时出错", e);
        }
    }

    public void setLookupPath(String lookupPath) {
        this.lookupPath = lookupPath;
    }

}
